package com.study.common.jpush.service.impl;

import com.study.common.jpush.domain.PushBean;
import com.study.common.jpush.service.IJPushService;
import com.study.common.jpush.service.IMyJPushService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
public class MyJPushServiceImpl implements IMyJPushService {

    /**
     * 一次推送最大数量 (极光限制1000)
     */
    private static final int max_size = 800;

    private final IJPushService ijPushService;

    /**
     * 全部推送
     *
     * @param pushBean
     * @return
     */
    @Override
    public boolean pushAll(PushBean pushBean) {
        return ijPushService.pushAll(pushBean);
    }

    /**
     * 推送全部IOS
     *
     * @param pushBean
     * @return
     */
    @Override
    public boolean pushIos(PushBean pushBean) {
        return ijPushService.pushIos(pushBean);
    }

    /**
     * @param pushBean
     * @param registids
     * @return
     */
    @Override
    public boolean pushIos(PushBean pushBean, String... registids) {
        registids = checkRegistids(registids); //// 剔除无效registed
        while (registids.length > max_size) {
            ijPushService.pushIos(pushBean, Arrays.copyOfRange(registids, 0, max_size));
            registids = Arrays.copyOfRange(registids, max_size, registids.length);
        }
        return ijPushService.pushIos(pushBean, registids);
    }

    @Override
    public boolean pushAndroid(PushBean pushBean) {
        return ijPushService.pushAndroid(pushBean);
    }

    @Override
    public boolean pushUserKey(PushBean pushBean, String deviceToken) {
        return ijPushService.pushUserKey(pushBean, deviceToken);
    }

    @Override
    public boolean pushAndroid(PushBean pushBean, String... registids) {
        registids = checkRegistids(registids); //// 剔除无效registed
        while (registids.length > max_size) {
            ijPushService.pushAndroid(pushBean, Arrays.copyOfRange(registids, 0, max_size));
            registids = Arrays.copyOfRange(registids, max_size, registids.length);
        }
        return ijPushService.pushAndroid(pushBean, registids);
    }

    /**
     * 剔除无效registed
     *
     * @param registids
     * @return
     */
    @Override
    public String[] checkRegistids(String[] registids) {
        List<String> regList = new ArrayList<String>(registids.length);
        for (String registid : registids) {
            if (registid != null && !"".equals(registid.trim())) {
                regList.add(registid);
            }
        }
        return regList.toArray(new String[0]);
    }
}
